package com.fafian.publish.json;

import java.util.Map;

import com.fafian.publish.SynchronousWorker;
import com.fafian.publish.SynchronousWorkerException;
import com.fafian.publish.json.exceptions.JSONWorkerInitException;
import com.google.gson.Gson;

public abstract class JSONAbstractSynchronousWorker<S,T> implements
		SynchronousWorker<String, String> {

	private Gson gson;
	private String uri;
	
	public JSONAbstractSynchronousWorker(String uri){
		gson = new Gson();
		this.uri = uri;
	}
	
	public JSONAbstractSynchronousWorker(){
		this(null);
	}
	
	@Override
	public final String process(String toProcess) throws SynchronousWorkerException {
		if (toProcess == null){
			throw new SynchronousWorkerException("Request string is null");
		}
		try{
			S toReturn = processObject(gson.fromJson(toProcess, getRequestClass()));
			if (toReturn == null){
				throw new SynchronousWorkerException("Result is null");
			}
			return gson.toJson(toReturn);
		} catch (Exception e){
			throw new SynchronousWorkerException(e);
		}
		
	}

	public final void setUri(String uri){
		this.uri = uri;
	}
	
	public final String getUri(){
		return uri;
	}
	
	protected abstract Class<T> getRequestClass();
	protected abstract S processObject(T toProcess);
	protected abstract void init(Map<String, String> parameters) throws JSONWorkerInitException;
	
	@Override
	public final String getTargetName() {
		return JSONStringBus.BASE_NAME+"-"+uri;
	}

}
